package cn.caplike.demo.consistence.threadpool.and.blockingqueue.context;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Redis 的操作类
 *
 * @author LiKe
 * @version 1.0.0
 * @date 2020-03-18 14:32
 */
@Component
@Slf4j
public class RedisUtils {

    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * Description: 指定缓存失效的时间
     *
     * @return java.lang.Boolean
     * @author LiKe
     * @date 2020-03-18 14:43:08
     */
    public Boolean expire(String key, long expireTime) {
        if (expireTime < 0) {
            throw new RuntimeException("超时时间不能小于0");
        }

        return this.redisTemplate.expire(key, expireTime, TimeUnit.MICROSECONDS);
    }

    /**
     * Description: 判断是否有指定 key
     *
     * @return java.lang.Boolean
     * @author LiKe
     * @date 2020-03-18 14:43:48
     */
    public Boolean hasKey(String key) {
        return this.redisTemplate.hasKey(key);
    }

    /**
     * Description: 保存
     *
     * @return void
     * @author LiKe
     * @date 2020-03-18 14:47:56
     */
    public void save(String key, Object value) {
        this.redisTemplate.opsForValue().set(key, value);
    }

    /**
     * Description: 删除 key
     *
     * @return java.lang.Boolean
     * @author LiKe
     * @date 2020-03-18 14:48:51
     */
    public Boolean delete(String key) {
        return this.redisTemplate.delete(key);
    }

    /**
     * Description: 保存有失效时间的键值对
     *
     * @return java.lang.Boolean
     * @author LiKe
     * @date 2020-03-18 14:49:35
     */
    public void save(String key, Object value, long expireTime) {
        this.redisTemplate.opsForValue().set(key, value, expireTime);
    }

    /**
     * Description: 获取指定 key 的值
     *
     * @return java.lang.Object
     * @author LiKe
     * @date 2020-03-18 16:37:16
     */
    public Object get(String key) {
        return this.redisTemplate.opsForValue().get(key);
    }

}
